/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package client;

import test_tim.*;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import javax.swing.WindowConstants;

/**
 *
 * @author timbeer
 */
public class Client implements Runnable {

    private int id;
    private String name;
    private Socket socket;
    private ObjectInputStream ois;
    private ObjectOutputStream oos;
    private String host;
    private int port;
    private Spiel spiel;
    private GUImainTest gui;
    
    //Klassenvariable
    private static int counter = 0;

    
    
    public Client(String host, int port, String name) {

//       this.host = host;
//       this.port = port;
//       this.name = name;
       this.id = counter;
       counter++;
        
        
        //connect to server
        try {
            socket = new Socket(host, port);

            System.out.println("Verbindung zu Port " + socket);

            ois = new ObjectInputStream(socket.getInputStream());
            oos = new ObjectOutputStream(socket.getOutputStream());

            new Thread(this).start();
        } catch (IOException ioe) {
            System.out.println(ioe);
        }
//        gui = new GUImainTest();
//        gui.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
//        gui.setSize(400, 400);
//        gui.setVisible(true);
    }

    //send the Object
    public void sendeObjekt(Spiel spiel) {
        try {
            oos.writeObject(spiel);

        } catch (IOException ioe) {
            System.out.println(ioe);
        }
    }

    //receive Objects forever
    @Override
    public void run() {

        try {
            while (true) {
                try {
                    spiel = (Spiel) ois.readObject();
                    gui.updateFields(spiel);
                    
                } catch (ClassNotFoundException ex) {
                    System.out.println(ex.toString());
                }
            }

        } catch (IOException ie) {
            System.out.println(ie.toString());
        }
    }
    
    public String getName(){
        return this.name;
    }
    
    public int getID(){
        return this.id;
    }
}
